package main

import (
	"strconv"

	"github.com/lxn/walk"
	"github.com/xuri/excelize/v2"
)

var (
	err               error
	dia               *walk.Dialog
	verticalWidget_1  *walk.Composite
	sheetList         *walk.ListBox
	sheetEdit         *walk.LineEdit
	addSheetBtn       *walk.PushButton
	rnmSheetBtn       *walk.PushButton
	delSheetBtn       *walk.PushButton
	verticalWidget_2  *walk.Composite
	tableView         *walk.TableView
	horzontalLayout_2 *walk.Composite
	addNameBtn        *walk.PushButton
	modNameBtn        *walk.PushButton
	delNameBtn        *walk.PushButton
	clearNameBtn      *walk.PushButton
)

func showEdit() {
	var nameModel = &listBoxModel{
		items: []string{},
	}

	// font
	font, err = walk.NewFont("Seogo UI", 12, 0)

	// dialog
	dia, err = walk.NewDialog(mw)
	ifErr(err)
	err = dia.SetTitle("编辑档案")
	ifErr(err)
	err = dia.SetMinMaxSize(walk.Size{600, 370}, walk.Size{600, 370})
	ifErr(err)
	err = dia.SetLayout(walk.NewHBoxLayout())
	ifErr(err)
	dia.SetFont(font)

	// verticalWidget_1
	verticalWidget_1, err = walk.NewComposite(dia)
	ifErr(err)
	err = verticalWidget_1.SetLayout(walk.NewVBoxLayout())
	ifErr(err)

	// sheetList
	sheetList, err = walk.NewListBox(verticalWidget_1)
	ifErr(err)
	err = sheetList.SetModel(nameModel)
	ifErr(err)
	nameModel.SetValue(sheetsList)
	sheetList.CurrentIndexChanged().Attach(updateEditTable)
	err = sheetList.SetCurrentIndex(0)
	ifErr(err)

	// sheetEdit
	sheetEdit, err = walk.NewLineEdit(verticalWidget_1)
	ifErr(err)

	// addSheetBtn
	addSheetBtn, err = walk.NewPushButton(verticalWidget_1)
	ifErr(err)
	err = addSheetBtn.SetText("新建")
	ifErr(err)

	// rnmSheetBtn
	rnmSheetBtn, err = walk.NewPushButton(verticalWidget_1)
	ifErr(err)
	err = rnmSheetBtn.SetText("重命名")
	ifErr(err)

	// delSheetBtn
	delSheetBtn, err = walk.NewPushButton(verticalWidget_1)
	ifErr(err)
	err = delSheetBtn.SetText("删除")
	ifErr(err)
	if len(sheetsList) <= 1 {
		delSheetBtn.SetEnabled(false)
	}

	// verticalWidget_2
	verticalWidget_2, err = walk.NewComposite(dia)
	ifErr(err)
	err = verticalWidget_2.SetLayout(walk.NewVBoxLayout())
	ifErr(err)

	// tableView
	tableView, err = walk.NewTableView(verticalWidget_2)
	ifErr(err)
	err = tableView.SetModel(editTable)
	ifErr(err)
	SetHead(tableView)
	updateEditTable()

	// horizontalLayout_2
	horzontalLayout_2, err = walk.NewComposite(verticalWidget_2)
	ifErr(err)
	err = horzontalLayout_2.SetLayout(walk.NewHBoxLayout())
	ifErr(err)

	// addNameBtn
	addNameBtn, err = walk.NewPushButton(horzontalLayout_2)
	ifErr(err)
	err = addNameBtn.SetText("添加")
	ifErr(err)

	// modNameBtn
	modNameBtn, err = walk.NewPushButton(horzontalLayout_2)
	ifErr(err)
	err = modNameBtn.SetText("修改")
	ifErr(err)
	modNameBtn.SetEnabled(false)

	// delNameBtn
	delNameBtn, err = walk.NewPushButton(horzontalLayout_2)
	ifErr(err)
	err = delNameBtn.SetText("删除")
	ifErr(err)
	delNameBtn.SetEnabled(false)

	// clearNameBtn
	clearNameBtn, err = walk.NewPushButton(horzontalLayout_2)
	ifErr(err)
	err = clearNameBtn.SetText("清空")
	ifErr(err)

	// 将文件拖入到listBox中
	sheetList.DropFiles().Attach(func(files []string) {
		var (
			alreadyExistName string
			FailedFile       string
		)
		for _, file := range files {
			f, err := excelize.OpenFile(file)
			if err != nil {
				FailedFile += file + "\n"
				continue
			}
			for _, sheet := range f.GetSheetList() {
				sheetIndex := c.GetSheet(sheet)
			OuterLoop:
				for row := 1; true; row++ {
					name, err := f.GetCellValue(sheet, "A"+strconv.Itoa(row))
					if err != nil {
						walk.MsgBox(nil, "读取单元格错误", "在读取A"+strconv.Itoa(row)+"时出错", walk.MsgBoxIconWarning)
						continue
					}
					if name == "" {
						break
					}
					label, err := f.GetCellValue(sheet, "B"+strconv.Itoa(row))
					if err != nil {
						walk.MsgBox(nil, "读取单元格错误", "在读取B"+strconv.Itoa(row)+"时出错", walk.MsgBoxIconWarning)
						continue
					}
					groupIndex := c.GetGroup(sheetIndex, label)
					if c.NameSheets[sheetIndex].checkNameExist(name) {
						alreadyExistName += name + "\n"
						continue OuterLoop
					}
					c.NameSheets[sheetIndex].LabelGroups[groupIndex].Names = append(
						c.NameSheets[sheetIndex].LabelGroups[groupIndex].Names,
						name,
					)
					saveConfig()
					updateSheetList()
					nameModel.SetValue(sheetsList)
					err = sheetList.SetCurrentIndex(len(sheetsList) - 1)
					ifErr(err)
				}
			}
			err = f.Close()
			ifErr(err)
		}
		err = mw.ui.comboBox.SetModel(sheetsList)
		ifErr(err)
		if FailedFile != "" {
			walk.MsgBox(dia, "打开文件失败", "打开以下表格文件时出错，已自动跳过\n"+FailedFile, walk.MsgBoxIconWarning)
		}
		if alreadyExistName != "" {
			walk.MsgBox(dia, "姓名已存在", "以下姓名已经存在，自动跳过导入：\n"+alreadyExistName, walk.MsgBoxIconWarning)
		}
		delSheetBtn.SetEnabled(true)
	})

	// 改变按钮的禁用状态
	tableView.CurrentIndexChanged().Attach(func() {
		if tableView.CurrentIndex() < 0 {
			modNameBtn.SetEnabled(false)
			delNameBtn.SetEnabled(false)
		} else {
			modNameBtn.SetEnabled(true)
			delNameBtn.SetEnabled(true)
		}
	})

	// 新建姓名表
	addSheetBtn.Clicked().Attach(func() {
		addSheetEvent(nameModel)
	})
	sheetEdit.KeyUp().Attach(func(key walk.Key) {
		if key == walk.KeyReturn {
			addSheetEvent(nameModel)
		}
	})

	// 重命名姓名表
	rnmSheetBtn.Clicked().Attach(func() {
		name := sheetEdit.Text()
		if checkSheetExist(name) {
			index := sheetList.CurrentIndex()
			if name == "" {
				walk.MsgBox(dia, "重命名失败", "请在输入框中输入名称", walk.MsgBoxIconWarning)
				return
			}
			c.NameSheets[index].Sheet = name
			saveConfig()
			updateSheetList()
			nameModel.SetValue(sheetsList)
			err = sheetList.SetCurrentIndex(index)
			ifErr(err)
			err = mw.ui.comboBox.SetModel(sheetsList)
			ifErr(err)
		} else {
			walk.MsgBox(dia, "重命名失败", "输入的表已存在", walk.MsgBoxIconWarning)
		}
	})

	// 删除姓名表
	delSheetBtn.Clicked().Attach(func() {
		delSheet(nameModel)
	})
	sheetList.KeyUp().Attach(func(key walk.Key) {
		if key == walk.KeyDelete {
			delSheet(nameModel)
		}
	})

	// 新建姓名
	addNameBtn.Clicked().Attach(func() {
		name, label := showMod("新建姓名", "", "")
		if name == "" {
			return
		}
		sheetIndex := sheetList.CurrentIndex()
		groupIndex := c.GetGroup(sheetIndex, label)
		if !c.NameSheets[sheetIndex].checkNameExist(name) {
			l := &c.NameSheets[sheetIndex].LabelGroups[groupIndex].Names
			*l = append(*l, name)
			saveConfig()
			updateEditTable()
			updateNameList()
			updateLabelList()
			updateNameTable()
		} else {
			walk.MsgBox(dia, "新建失败", "输入的姓名已经存在", walk.MsgBoxIconWarning)
		}
	})

	// 修改姓名
	modNameBtn.Clicked().Attach(func() {
		name, label := showMod("修改姓名", editTable.items[tableView.CurrentIndex()].Name, editTable.items[tableView.CurrentIndex()].Label)
		if name == "" {
			return
		}
		sheetIndex := sheetList.CurrentIndex()
		groupIndex := c.GetGroup(sheetIndex, label)
		if !c.NameSheets[sheetIndex].checkNameExist(name) || name == editTable.items[tableView.CurrentIndex()].Name {
			l := &c.NameSheets[sheetIndex].LabelGroups[groupIndex].Names
			delName(editTable.items[tableView.CurrentIndex()].Name, sheetIndex, c.GetGroup(sheetIndex, editTable.items[tableView.CurrentIndex()].Label))
			*l = append(*l, name)
			saveConfig()
			updateEditTable()
			updateNameTable()
			updateLabelList()
			updateNameList()
		} else {
			walk.MsgBox(dia, "修改失败", "输入的姓名已经存在", walk.MsgBoxIconWarning)
		}
	})

	// 删除姓名
	delNameBtn.Clicked().Attach(func() {
		delName(editTable.items[tableView.CurrentIndex()].Name, sheetList.CurrentIndex(), c.GetGroup(sheetList.CurrentIndex(), editTable.items[tableView.CurrentIndex()].Label))
		updateEditTable()
	})
	tableView.KeyUp().Attach(func(key walk.Key) {
		if key == walk.KeyDelete {
			delName(editTable.items[tableView.CurrentIndex()].Name, sheetList.CurrentIndex(), c.GetGroup(sheetList.CurrentIndex(), editTable.items[tableView.CurrentIndex()].Label))
			updateEditTable()
		}
	})

	// 清空姓名
	clearNameBtn.Clicked().Attach(func() {
		if sheetList.CurrentIndex() < 0 {
			return
		}
		c.NameSheets[sheetList.CurrentIndex()] = nameSheet{
			Sheet:       c.NameSheets[sheetList.CurrentIndex()].Sheet,
			LabelGroups: []labelGroup{},
		}
		saveConfig()
		updateEditTable()
	})

	dia.Run()
	dia.Dispose()
}

// 更新姓名表控件模型（从配置文件中）
func updateEditTable() {
	if sheetList.CurrentIndex() < 0 {
		return
	}
	var et []NameTableItem
	for _, g := range c.NameSheets[sheetList.CurrentIndex()].LabelGroups {
		for _, n := range g.Names {
			et = append(et, NameTableItem{
				Name:  n,
				Label: g.Label,
			})
		}
	}
	editTable.SetValue(et)
}

// 删除姓名表
func delSheet(nameModel *listBoxModel) {
	index := sheetList.CurrentIndex()
	c.NameSheets = append(c.NameSheets[:index], c.NameSheets[index+1:]...)
	saveConfig()
	updateSheetList()
	if index >= len(sheetsList) {
		index--
	}
	nameModel.SetValue(sheetsList)
	err = mw.ui.comboBox.SetModel(sheetsList)
	ifErr(err)
	err = sheetList.SetCurrentIndex(index)
	ifErr(err)
	if len(sheetsList) <= 1 {
		delSheetBtn.SetEnabled(false)
	}
}

// 删除姓名
func delName(n string, sheetIndex int, labelIndex int) {
	var nl []string
	for _, v := range c.NameSheets[sheetIndex].LabelGroups[labelIndex].Names {
		if v != n {
			nl = append(nl, v)
		}
	}
	c.NameSheets[sheetIndex].LabelGroups[labelIndex].Names = nl
	saveConfig()
}

// 添加新姓名表（事件用）
func addSheetEvent(nameModel *listBoxModel) {
	name := sheetEdit.Text()
	if checkSheetExist(name) {
		if name == "" {
			walk.MsgBox(dia, "新建失败", "请在输入框中输入新表名称", walk.MsgBoxIconWarning)
			return
		}
		addSheet(name)
		nameModel.SetValue(sheetsList)
		err = sheetList.SetCurrentIndex(len(sheetsList) - 1)
		ifErr(err)
		err = mw.ui.comboBox.SetModel(sheetsList)
		ifErr(err)
	} else {
		walk.MsgBox(dia, "新建失败", "输入的表已存在", walk.MsgBoxIconWarning)
	}
	err = sheetEdit.SetText("")
	ifErr(err)
	delSheetBtn.SetEnabled(true)
}

// 添加新姓名表
func addSheet(name string) {
	c.NameSheets = append(c.NameSheets, nameSheet{
		Sheet: name,
		LabelGroups: append([]labelGroup{}, labelGroup{
			Label: "",
			Names: []string{},
		}),
	})
	saveConfig()
	updateSheetList()
}

// 检查表是否存在
func checkSheetExist(sheet string) bool {
	for _, v := range sheetsList {
		if v == sheet {
			return false
		}
	}
	return true
}
